import type { Polygon } from 'geojson'
import { keyGen } from '@/common'
import { geometryOfSector, type LngLat } from '@/geom/great-circle'
import type { MapFeatures } from '@/map'
import { addAuxGraphic, auxGraphicProperties, type AuxGraphic } from '../core'

export interface AuxSector extends AuxGraphic {
  type: 'Sector'
  center: LngLat
  radius: number
  bearing1: number
  bearing2: number
}
const nameGen = keyGen('辅助扇形#')

function nextName(): string {
  return nameGen.next()
}
export function addAuxSector(center: LngLat, radius: number, bearing1: number, bearing2: number) {
  addAuxGraphic<AuxSector>({
    type: 'Sector',
    name: nextName(),
    center,
    radius,
    bearing1,
    bearing2
  })
}

export function toPolygon(as: AuxSector): Polygon {
  return geometryOfSector(as.center, as.radius, as.bearing1, as.bearing2, 40)
}

export function toFeature(ac: AuxSector, g: Polygon[]): MapFeatures {
  const geometry = g.length > 0 ? g[0] : toPolygon(ac)
  return {
    symbol: [
      {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: [ac.center.lng, ac.center.lat]
        },
        properties: auxGraphicProperties.symbol(ac.name)
      }
    ],
    line: [
      {
        type: 'Feature',
        geometry,
        properties: auxGraphicProperties.line
      }
    ]
  }
}
